<template>
	<z-paging ref="paging" v-model="dataList" @query="queryList"
		:loading-more-custom-style="{ paddingBottom: 'env(safe-area-inset-bottom)' }">
		<template #top>
			<view class="zpagin_top">
				<nav-bar :iconLeft="true" />
				<up-tabs :list="list" lineWidth="25" @change="tab_change" :scrollable="false"></up-tabs>
				<view class="search">
					<custom-search v-model="queryParams.search" @search="refreshList" placeholder="请输入计划号/客户名称" />
				</view>
				<dui-float-ball :pathUrl="`${pageUrl}/compile`" v-if="$hasPerm(['70201'])" />
			</view>
		</template>
		<u-swipe-action>
			<u-swipe-action-item v-for="item in dataList" :key="item.id"
				:name="JSON.stringify(swipeActPer(options, item.status_display)) + '&' + item.id + '&' + item.code"
				:options="swipeActPer(options, item.status_display)"
				:disabled="swipeActPer(options, item.status_display, 'disabled')" @click="action">
				<uni-card margin="0" spacing="0" @click="goDetail(item, pageUrl, '70204')">
					<template v-slot:title>
						<uni-list>
							<uni-list-item :title="item.code" thumbSize="lg">
								<template v-slot:footer>
									<up-tag size="mini" :text="status_list[item.status_display].text" plain plainFill
										:type="status_list[item.status_display].type" />
								</template>
							</uni-list-item>
						</uni-list>
					</template>
					<view class="ctent">客户名称：{{ item.client_name }}</view>
					<view class="ctent">交货日期：{{ item.delivery_date }}</view>
					<view class="ctent">预计完成日期：{{ item.finish_date }}</view>
					<view class="con">
						<view class="ctent">生产数量：{{ item.all_num }}</view>
						<view class="ctent">应领料数：{{ item.all_f_num }}</view>
					</view>
					<view class="con">
						<view class="ctent">生成生产单：{{ item.if_order_display }}</view>
						<view class="ctent">生成采购单：{{ item.if_purchase_display }}</view>
					</view>
					<view class="con">
						<view class="ctent">制单人：{{ item.create_full_name }}</view>
						<view class="ctent">审核人：{{ item.apply_full_name || '' }}</view>
					</view>
					<view class="con">
						<view class="con_button" v-if="$hasPerm(['70206'])" v-show="item.status_display == '待审核'"
							@click.stop="hanldAct(item.id, 'apply')"> 审核
						</view>
						<view class="con_button" v-if="$hasPerm(['70205'])" v-show="item.if_order_display == '否'"
							@click.stop="hanldAct(item.id, 'MRP', item)">
							MRP </view>
						<view class="con_button" v-if="$hasPerm(['70208'])"
							v-show="item.status_display == '已审核' && item.if_order_display == '否'"
							@click.stop="hanldAct(item.id, 'production')"> 生产
						</view>
					</view>
				</uni-card>
			</u-swipe-action-item>
		</u-swipe-action>
		<template #bottom>
			<custom-popup :popupShow="deta_popupShow" mode="center" :title="'MRP计算'" width="96%" height="70%"
				class="car-popup-custom" @close="deta_popupShow = false" :closeOnClickOverlay="false">
				<z-paging v-if="deta_popupShow" ref="deta_paging" :fixed="false" :refresher-enabled="false" :loading-more-enabled="false" v-model="deta_list"
					@query="queryList_deta">
					<uni-card v-for="item in deta_list" :title="item.bom_name" :sub-title="item.product_name" :key="item.id"
						margin="5px" spacing="0">
						<view class="ctent">规格：{{ item.bom_specification }}</view>
						<view class="con">
							<view class="ctent">库存：{{ item.bom_inventory }}</view>
							<view class="ctent">采购未入库：{{ item.remaining }}</view>
						</view>
						<view class="con">
							<view class="ctent">生产计划占用：{{ item.plan_bom_num }}</view>
							<view class="ctent">生产单待领料：{{ item.issue_num }}</view>
						</view>
						<view class="con">
							<view class="ctent">委外待发料：{{ item.machining_num }}</view>
							<view class="ctent">不足数：{{ item.deficiency_num }}</view>
						</view>
					</uni-card>
					<template #bottom>
						<uni-card margin="0" spacing="0">
							<view class="ctent">MRP 五个围度：</view>
							<view class="ctent">1、仓库剩余货品（不含“不良品仓”和“废品仓”）存量的</view>
							<view class="ctent">2、采购单中已审核并且未结单的剩余未入库部分的</view>
							<view class="ctent">3、生产计划占用（未生成生产单）的</view>
							<view class="ctent">4、生产单未结单待领料的</view>
							<view class="ctent">5、委外加工单待发料的</view>
							<view class="ctent" style="color: red;">可用量 = 库存 + 采购中 - 生产计划占用 - 生产单(待领料) - 委外单(待发料)</view>
							<view class="ctent" style="color: red;">该计划单形成生产单后，将不再计算MRP</view>
							<view>
								<u-button type="primary" size="small" style="display: inline-flex;width: auto;" text="生成采购单"
									@click="create_purchase_plan" v-show="purchase_plan"></u-button>
							</view>
						</uni-card>
						<up-modal :show="show_cg" @confirm="confirm_cg" @cancal="cancal_cg" ref="uModal" title="生成采购计划？"
							:asyncClose="true">
							<uni-datetime-picker type="date" :clear-icon="false" v-model="cg_date" />
						</up-modal>
					</template>
				</z-paging>
			</custom-popup>
		</template>
	</z-paging>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import pPlanApi from '../../../api/production/p_plan'
import { debounce, generateCode } from '@/utils/index.js' // 用防抖优化请求频率（下面给出）
import { swipeActPer, goDetail } from '@/utils/permission'

uni.$bus.useBusOn('p_plan:refresh', refreshList)

const options = [
	{
		text: '修改', per: '70202',
		style: {
			backgroundColor: '#0081ff'
		}
	}, {
		text: '删除', per: '70203',
		style: {
			backgroundColor: '#f56c6c'
		}
	}
]
const list = [
	{ name: '待审核', status: '1' },
	{ name: '已审核', status: '2' }
]

const status_list = {
	'待审核': { text: '待审核', type: 'warning' },
	'已审核': { text: '已审核', type: 'success' }
}

const tab_change = debounce(function (v) {
	queryParams.status = v.status;
	refreshList();
}, 500)

const pageUrl = '/views/production/p_plan'

//数据请求
const paging = ref(null);
const dataList = ref([]);
const queryParams = reactive({
	search: '',
	status: ''
})
function queryList(pageNo, pageSize) {
	const params = {
		page: pageNo,
		page_size: pageSize,
		...queryParams
	}
	pPlanApi.get_production_plan(params).then((res) => {
		paging.value.complete(res.results);
	})
}

const MRP_id = ref(false)
const edit_row = reactive({})
function hanldAct(id, key, record) {
	let status = null
	let text = ''
	if (key == 'apply') {
		status = 2
		text = '审核成功'
		const params = {
			status, if_handle: 1
		}
		pPlanApi.patch_production_plan(params, id).then(res => {
			uni.$u.toast(text)
			setTimeout(() => {
				refreshList();
			}, 500)
		})
	}
	if (key == 'MRP') {
		Object.assign(edit_row, record)
		MRP_id.value = id
		deta_popupShow.value = true
	}
	if (key == 'production') {
		uni.showModal({
			title: '提示',
			content: '确定要生成生产单吗？',
			success: (res) => {
				if (res.confirm) {
					pPlanApi.create_production_order({ plan_id: id }).then(() => {
						uni.$u.toast('生成成功')
						refreshList();
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}
}

const deta_popupShow = ref(false)
const deta_paging = ref(null)
const deta_list = ref([])
const purchase_plan = ref(false)
function queryList_deta() {
	const params = { plan_id: MRP_id.value }
	pPlanApi.post_production_plan_mrp(params).then(res => {
		deta_paging.value.complete(res.results);
		const total_deficiency_num = res.results.reduce((num, item) => {
			return num += item.deficiency_num
		}, 0)
		if (total_deficiency_num) {
			purchase_plan.value = true
		} else {
			purchase_plan.value = false
		}
	})
}

const show_cg = ref(false)

function create_purchase_plan() {
	if (edit_row.status !== 2) {
		uni.$u.toast('计划单未审核')
		return
	}
	if (edit_row.if_purchase_display === '是') {
		uni.$u.toast('当前计划单已生成或生成过采购单，请勿再次生成')
		return
	}
	show_cg.value = true
}

const cg_date = ref('')
function confirm_cg() {
	if (!cg_date.value) {
		uni.$u.toast('请选择交货日期')
	}
	const bom_list = []
	deta_list.value.forEach(v => {
		if (v.bom_style === 1) {
			bom_list.push({
				p_supplier_id: v.bom_default_supplier_id,
				p_supplier_price: v.bom_default_supplier_price,
				id: v.bom_id,
				specification: v.bom_specification,
				p_unit: v.bom_unit,
				loss: v.bom_loss,
				p_num: v.deficiency_num
			})
		}
	})
	const params = {
		delivery_date: cg_date.value,
		bom_list: bom_list,
		code: generateCode('PL'),
		if_production_plan: 1,
		production_plan_id: edit_row.id
	}
	pPlanApi.post_purchase_plan(params).then(res => {
		uni.$u.toast('生成采购计划成功')
		show_cg.value = false;
		setTimeout(() => {
			show_cg.value = false
			refreshList();
		}, 500)
	})
}

function cancal_cg() {
	show_cg.value = false
	cg_date.value = ''
}

//滑动操作按钮
function action(v) {
	const options = JSON.parse(v.name.split("&")[0])
	const id = v.name.split("&")[1]
	const delName = '单号为：' + v.name.split("&")[2]
	const index = v.index
	if (options[index].text == '修改') {
		uni.navigateTo({
			url: `${pageUrl}/compile?type=edit&id=${id}`
		})
	}
	if (options[index].text == '删除') {
		delete_type(id, delName)
	}
}
//删除操作
function delete_type(id, delName) {
	uni.showModal({
		title: '提示',
		content: `确认要删除单号为：【${delName}】的数据项吗？`,
		success: (res) => {
			if (res.confirm) {
				pPlanApi.delete_production_plan(id).then((res) => {
					uni.$u.toast('删除成功')
					setTimeout(() => {
						refreshList();
					}, 500)
				})
			}
		}
	});
}
//编辑跳转刷新
function refreshList() {
	paging.value.reload();
}

</script>

<style lang="scss"></style>